<!--
 * @Author: Penk
 * @LastEditors: Penk
 * @LastEditTime: 2022-11-10 23:59:38
 * @FilePath: \web面试题\黑夜下雪.html
 * @email: 492934056@qq.com
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>黑夜下雪</title>
  </head>
  <body style="margin: 0">
    <canvas id="myCanvas" style="background-color: #000"></canvas>

    <script>
      // 通过解构，获取屏幕宽高
      const { clientWidth: width, clientHeight: height } =
        document.documentElement;

      console.log(`width:${width}...`);
      console.log(`height:${height}...`);
      let ctx = document.getElementById("myCanvas");
      if (ctx && ctx.getContext) {
        // 初始化画布
        init();
        // 画白点
        var pointArr = drawPoint(400);
        // 渲染
        render();
      }

      // 初始化画布
      function init() {
        ctx.width = width;
        ctx.height = height;
        ctx = ctx.getContext("2d");
        ctx.fillStyle = "#fff";
      }

      // 画白点
      function drawPoint(num) {
        return Array.from(new Array(num)).map((item) => {
          return {
            x: Math.random() * width,
            y: Math.random() * height,
            s: Math.random() * 3 + 0.2,
          };
        });
      }

      // 渲染
      function render() {
        ctx.clearRect(0, 0, width, height);
        pointArr.forEach((item) => {
          ctx.beginPath();
          item.y = item.y > height ? 0 : item.y + item.s;
          ctx.arc(item.x, item.y, 3, 0, 2 * Math.PI);
          ctx.fill();
        });
        ctx.stroke();

        requestAnimationFrame(render);
      }
    </script>
  </body>
</html>
